package com.bidevalution.business.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.bidevalution.business.function.FunctionCalculator;
import com.bidevalution.business.service.BeSectionColumnService;
import com.bidevalution.business.service.BeSectionParameterService;
import com.bidevalution.dao.entity.BeSectionColumn;
import com.bidevalution.dao.entity.BeSectionExpertInfo;
import com.bidevalution.dao.entity.BeSectionLayout;
import com.bidevalution.dao.entity.BeSectionParameter;
import com.bidevalution.dao.mapper.BeSectionColumnMapper;
import com.bidevalution.service.layout.ColumnConfig;
import com.bidevalution.service.layout.ColumnHeader;
import com.bidevalution.service.layout.ColumnHeader.ColumnType;
import com.bidevalution.support.exception.BizException;
import com.bidevalution.support.util.LogUtil;
import com.bidevalution.support.util.StringUtil;
import com.google.common.collect.Maps;
import com.qtp.core.util.GsonUtil;

@Service
public class BeSectionColumnServiceImpl implements BeSectionColumnService {
	@Autowired
	private BeSectionColumnMapper beSectionColumnMapper;
	@Autowired
	private BeSectionParameterService beSectionParameterService;
	private LogUtil logUtil = LogUtil.getLogManager(getClass());

	/**
	 * @throws Exception 获取表格字段 @param @param sectionStepId @param @param
	 *                   layoutCode @param @param isFinish @param @param
	 *                   sectionParameterList @param @return 参数 @return
	 *                   List<ColumnHeader> 返回类型 @throws
	 */
	@Override
	public List<ColumnHeader> getColumnHeaderList(BeSectionExpertInfo beSectionExpertInfo, String sectionStepId,
			BeSectionLayout beSectionLayout, boolean isFinish) throws Exception {
		List<BeSectionColumn> beSectionColumnList = beSectionColumnMapper.selectList(sectionStepId,
				beSectionLayout.getLayoutCode());
		String enableEdit;
		List<ColumnHeader> columnHeaderList = new ArrayList<ColumnHeader>();
		ColumnHeader columnHeader;
		Map<String, Object> columnConfigMap;
		List<ColumnConfig> columnConfigList;
		// 返回给前端验证的js方法
		String validator;
		// 列单击触发的事件
		String clickFunction;
		// 默认值
		String defaultValue;
		List<BeSectionParameter> beSectionParameterList = beSectionParameterService
				.selectList(beSectionExpertInfo.getSectionId());
		Map<String, Object> permissionMap;
		for (BeSectionColumn beSectionColumn : beSectionColumnList) {
			enableEdit = beSectionColumn.getEnableEdit();
			// 创建表格字段
			columnHeader = new ColumnHeader(beSectionColumn.getColumnCode(), beSectionColumn.getColumnText(),
					beSectionColumn.getInputType(), beSectionColumn.getColumnWidth(),
					beSectionColumn.getClickFunction(), beSectionColumn.getFormulaConfig(), enableEdit,
					beSectionColumn.getValidator(), beSectionColumn.getColumnDescription());
			// 如果字段输入类型是下拉框，则构造前端页面下拉框显示的内容
			if (columnHeader.getColumnType().equals(ColumnType.SELECT.getCode())
					&& !StringUtils.isEmpty(beSectionColumn.getColumnConfig())) {
				columnConfigMap = (Map<String, Object>) GsonUtil.jsonToMapWithGson(beSectionColumn.getColumnConfig());
				columnConfigList = new ArrayList<ColumnConfig>();
				for (Entry<String, Object> entry : columnConfigMap.entrySet()) {
					columnConfigList.add(new ColumnConfig(entry.getKey(), StringUtil.toString(entry.getValue())));
				}
				columnHeader.setSelectConfig(columnConfigList);
			}

			// 替换validate可变参数值
			if (!StringUtils.isEmpty(columnHeader.getValidator())) {
				validator = columnHeader.getValidator();
				for (BeSectionParameter beSectionParameter : beSectionParameterList) {
					validator = validator.replaceAll("\\{PARAM_" + beSectionParameter.getParamId() + "\\}",
							beSectionParameter.getParamValue());
				}
				columnHeader.setValidator(validator);
			}
			// 替换列单击的js方法可变参数
			if (!StringUtils.isEmpty(columnHeader.getClickFunction())) {
				clickFunction = columnHeader.getClickFunction();
				for (BeSectionParameter beSectionParameter : beSectionParameterList) {
					clickFunction = clickFunction.replaceAll("\\{PARAM_" + beSectionParameter.getParamId() + "\\}",
							beSectionParameter.getParamValue());
				}
				columnHeader.setClickFunction(clickFunction);
			}
			// 替换默认值可变参数
			if (!StringUtils.isEmpty(columnHeader.getDefaultValue())) {
				defaultValue = columnHeader.getDefaultValue();
				for (BeSectionParameter beSectionParameter : beSectionParameterList) {
					defaultValue = defaultValue.replaceAll("\\{PARAM_" + beSectionParameter.getParamId() + "\\}",
							beSectionParameter.getParamValue());
				}
				columnHeader.setDefaultValue(defaultValue);
			}
			// 计算字段权限
			String permissionConfig = beSectionColumn.getPermissionConfig();
			if (!StringUtils.isEmpty(permissionConfig)) {
				permissionConfig = permissionConfig.trim();
				// 评标参数的值放入到公式计算参数中
				Map<String, Object> computeMap = Maps.newHashMap();
				for (BeSectionParameter beSectionParameter : beSectionParameterList) {
					computeMap.put("$PARAM_" + beSectionParameter.getParamId(), beSectionParameter.getParamValue());
				}
				computeMap.put("$EXPERT_TYPE", beSectionExpertInfo.getExpertType());
				computeMap.put("$IS_MANAGER", beSectionExpertInfo.getIsManager());
				permissionMap = Maps.newHashMap();
				permissionMap.putAll(computeMap);
				permissionMap.put("columnType", columnHeader.getColumnType());
				permissionMap.put("enableEdit", columnHeader.getEnableEdit());
				permissionMap.put("defaultValue", columnHeader.getDefaultValue());
				permissionMap.put("name", columnHeader.getName());
				permissionMap.put("memo", columnHeader.getMemo());
				computeMap.putAll(BeanUtils.describe(columnHeader));

				if (permissionConfig.toLowerCase().startsWith("{mel[")) {
					permissionConfig = permissionConfig.substring(5, permissionConfig.length() - 2);
					permissionConfig = FunctionCalculator.computeMVEL(permissionConfig, permissionMap);
				} else if (permissionConfig.toLowerCase().startsWith("{ael[")) {
					permissionConfig = permissionConfig.substring(5, permissionConfig.length() - 2);
					permissionConfig = FunctionCalculator.computeAviator(permissionConfig, permissionMap);
				} else
					throw new BizException("计算公式格式错误:" + permissionConfig);
				BeanUtils.setProperty(columnHeader, "columnType", permissionMap.get("columnType"));
				BeanUtils.setProperty(columnHeader, "enableEdit", permissionMap.get("enableEdit"));
				BeanUtils.setProperty(columnHeader, "defaultValue", permissionMap.get("defaultValue"));
				BeanUtils.setProperty(columnHeader, "name", permissionMap.get("name"));
				BeanUtils.setProperty(columnHeader, "memo", permissionMap.get("memo"));
			}

			if (!isFinish) {
				// 环节完成不可编辑
				columnHeader.setEnableEdit("0");
			}
			columnHeader.setDefaultValue(beSectionColumn.getDefaultValue());
			// 添加到返回结果中
			columnHeaderList.add(columnHeader);
		}
		// 添加序号
		if ("1".equals(beSectionLayout.getDisplayOrder())) {
			columnHeaderList.add(0, new ColumnHeader("LINENUMBER", "序号", "LINENUMBER", "", "", "", "0", "", ""));
		}
		return columnHeaderList;
	}
}
